﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class AMZ_MSKUInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters { get; set; }
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }
        public AMZ_MSKUInterfaceBusiness()
        {
            this.InterfaceName = "亚马逊MSKU";
            //获取字段的映射关系
            tableField = GetMapField("addRow");
            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            this.ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            this.SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //获取店铺
                OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
                OL_Shop.Filters.Add(
            new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
                //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
                shopList.ForEach(x =>
                {
                    //店铺
                    List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform_ = table.IsNullOrEmpty() ? "" : table.First().sid;
                });



                //获取源数据
                LX_AMZ_MSKUInterfaceBusiness LX_AMZ_MSKU = new LX_AMZ_MSKUInterfaceBusiness();
                List<AMZ_MSKU> sourceData = await LX_AMZ_MSKU.QueryAsync<AMZ_MSKU>(LX_AMZ_MSKU.LX_Query, SqlDb);
                //ID赋值
                foreach (var item1 in sourceData)
                {
                    //负责人信息
                    item1.principal_info_T = !item1.principal_info.IsNullOrEmpty() && item1.principal_info.Count > 0 ? string.Join(',', item1.principal_info.Select(x => x.principal_name)) : "";
                    //排名所属的类别
                    item1.seller_category_new_T = !item1.seller_category_new.IsNullOrEmpty() && item1.seller_category_new.Count > 0 ? string.Join(',', item1.seller_category_new) : "";
                    //尺寸信息，没有尺寸信息时是空
                    if (!item1.dimension_info.IsNullOrEmpty() && item1.dimension_info.Count > 0)
                    {
                        item1.item_height = item1.dimension_info[0].item_height;
                        item1.item_height_units_type = item1.dimension_info[0].item_height_units_type;
                        item1.item_length = item1.dimension_info[0].item_length;
                        item1.item_length_units_type = item1.dimension_info[0].item_length_units_type;
                        item1.item_width = item1.dimension_info[0].item_width;
                        item1.item_width_units_type = item1.dimension_info[0].item_width_units_type;
                        item1.item_weight = item1.dimension_info[0].item_weight;
                        item1.item_weight_units_type = item1.dimension_info[0].item_weight_units_type;
                        item1.package_height = item1.dimension_info[0].package_height;
                        item1.package_height_units_type = item1.dimension_info[0].package_height_units_type;
                        item1.package_length = item1.dimension_info[0].package_length;
                        item1.package_length_units_type = item1.dimension_info[0].package_length_units_type;
                        item1.package_width = item1.dimension_info[0].package_width;
                        item1.package_width_units_type = item1.dimension_info[0].package_width_units_type;
                        item1.package_weight = item1.dimension_info[0].package_weight;
                        item1.package_weight_units_type = item1.dimension_info[0].package_weight_units_type;
                    }
                    var shop = shopList.Where(x => x.ID == item1.sid);
                    if (!shop.IsNullOrEmpty())
                    {
                        item1.shop = shop.First().RowId;
                        item1.Platform_RowId = shop.First().Platform_;
                    }


                    item1.asinLink = "https://www.amazon.com/dp/" + item1.asin;
                    item1.ID = item1.seller_sku + item1.sid;
                }

                //获取最大时间和最小时间查询源数据
                //     var date = sourceData.OrderBy(x => x.shipmentsDateLocale).ToList();
                //     Filters.Clear();
                //     this.Filters.Add(
                //    //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "673b17917d6d0d88187c53a4", DataType = 15, SpliceType = 1, FilterType = 14, Value = date[0].shipmentsDateLocale.ToDateTime().ToString("yyyy-MM-dd") }//FDATE字段过滤日开始700天前到现在的数据
                //);
                //     this.Filters.Add(
                //    //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "673b17917d6d0d88187c53a4", DataType = 15, SpliceType = 1, FilterType = 16, Value = date[sourceData.Count - 1].shipmentsDateLocale.ToDateTime().ToString("yyyy-MM-dd") }//FDATE字段过滤日开始700天前到现在的数据
                //);


                //ID重复项
                var t = sourceData.GroupBy(x => x.ID).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();

                //获取目标数据
                List<AMZ_MSKU> targetData = new List<AMZ_MSKU>();//目标据集合
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "685aa0b5a31d84c7f659fa16", DataType = 30, SpliceType = 1, FilterType = 2, Value = "10001" }//只查询亚马逊的MSKU
                //);
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开
                );
                targetData = await QueryAsync<AMZ_MSKU>(queryOption, tableField, SqlDb);

                foreach (var item1 in targetData)
                {
                    item1.ID = item1.ID.Replace("\u200E", "");
                    item1.seller_sku = item1.seller_sku.Replace("\u200E", "");
                    //平台
                    List<AssTable> table = item1.Platform_RowId.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.Platform_RowId = table[0].sid;
                    else item1.Platform_RowId = "";
                    //店铺
                    table = item1.shop.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.shop = table[0].sid;
                    else item1.shop = "";
                }

                if (this.State > 0 && targetData.Count > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<AMZ_MSKU> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<AMZ_MSKU>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row_Update(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region

                    List<AMZ_MSKU> insertItem = sourceData.Except(targetData, new ComparerFromKey<AMZ_MSKU>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    //List<AMZ_MSKU> deleteItem = targetData.Except(sourceData, new ComparerFromKey<AMZ_MSKU>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<AMZ_MSKU> deleteItem = new List<AMZ_MSKU>();
                    List<AMZ_MSKU> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.ExecuteInterface<AMZ_MSKU>(targetData, "TD_OL_AMZ_MSKU", "", false);

                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {

                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row_Update<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
